import { HistorySession } from '@/interface'
import { BasicDataModule } from '@/store/modules/basicData'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { curry } from 'ramda'
/*
 * @Description:
 * @Author: fhw
 * @Date: 2022-12-30 11:31:46
 */
export const valueFormat = 'YYYY-MM-DD HH:mm:ss'
export const rangePickerShowTime = {
	defaultValue: [dayjs('00:00:00', 'HH:mm:ss'), dayjs('23:59:59', 'HH:mm:ss')],
}
/**
 * 时间转换
 * @param datetime 时间
 * @returns string
 */
export function formatTime(datetime: string): string {
	if (datetime == null) return ''
	datetime = dayjs(datetime).format('YYYY-MM-DD HH:mm:ss')
	const time = new Date()
	let outTime = new Date(datetime)
	if (/^[1-9]\d*$/.test(datetime)) {
		outTime = new Date(parseInt(datetime) * 1000)
	}

	if (time.getTime() < outTime.getTime() || time.getFullYear() != outTime.getFullYear()) {
		return parseTime(outTime, '{y}-{m}-{d} {h}:{i}')
	}

	if (time.getMonth() != outTime.getMonth()) {
		return parseTime(outTime, '{m}-{d} {h}:{i}')
	}

	if (time.getDate() != outTime.getDate()) {
		const day = outTime.getDate() - time.getDate()
		if (day == -1) {
			return parseTime(outTime, '昨天 {h}:{i}')
		}

		if (day == -2) {
			return parseTime(outTime, '前天 {h}:{i}')
		}

		return parseTime(outTime, '{m}-{d} {h}:{i}')
	}

	const diff = time.getTime() - outTime.getTime()

	if (time.getHours() != outTime.getHours() || diff > 30 * 60 * 1000) {
		return parseTime(outTime, '{h}:{i}')
	}

	let minutes = outTime.getMinutes() - time.getMinutes()
	if (minutes == 0) {
		return '刚刚'
	}

	minutes = Math.abs(minutes)
	return `${minutes}分钟前`
}
/**
 * 时间格式化方法
 *
 * @param {(Object|string|number)} time
 * @param {String} cFormat
 * @returns {String | null}
 */
export function parseTime(time: string | number | Date, cFormat: string): string {
	if (arguments.length === 0) {
		return ''
	}

	let date
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'

	if (typeof time === 'object') {
		date = time
	} else {
		if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
			time = parseInt(time)
		}
		if (typeof time === 'number' && time.toString().length === 10) {
			time = time * 1000
		}

		date = new Date((time as string).replace(/-/g, '/'))
	}

	const formatObj: ObjectMap = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay(),
	}
	const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
		const value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}

		return value.toString().padStart(2, '0')
	})

	return time_str
}
/**
 * 判断时间间隔多少小时
 * @param startTime 开始时间
 * @param endTime 结束时间
 * @returns 返回间隔时间
 */
export function judgeTimeDiffer(startTime: string, endTime: string) {
	const start = new Date(startTime)
	const end = new Date(endTime)
	return parseInt(String((start.getTime() - end.getTime()) / 1000 / 60 / 60))
}
export interface DebouncedFunc<T extends (...args: any[]) => any> {
	(...args: Parameters<T>): ReturnType<T> | undefined
}
/**
 * 函数防抖
 * @param func 要防抖的函数
 * @param wait 防抖时间 默认500ms
 */
export function throttle<T extends (...args: any) => any>(func: T, wait = 500): DebouncedFunc<T> {
	let leading = true
	return function (this: void, ...args: Array<any>) {
		if (!leading) {
			return {}
		}
		leading = false
		setTimeout(() => {
			leading = true
		}, wait)
		return func.apply(this, args)
	}
}
/**
 * 随机数
 * @param min 最小值
 * @param max 最大值
 * @returns number
 */
export function random(min: number, max: number) {
	return Math.floor(Math.random() * (max - min)) + min
}

//提示信息优化
function notificationTips(status: 'success' | 'error', description: string) {
	// notification[status]({
	// 	message: status === 'success' ? '成功' : '错误',
	// 	description,
	// })
	message[status](description)
}
const curryTips = curry(notificationTips)
export const successTips = curryTips('success')
export const errorTips = curryTips('error')
// 搜索过滤
export function searchFilter<T>(data: T[] | HistorySession[], inputValue: string) {
	return (data as HistorySession[]).filter((item) => {
		const isFriends = (item as HistorySession).friends?.username?.toUpperCase().includes(inputValue.toUpperCase())
		const isGroupChat = (item as HistorySession).groupChat?.groupChatName
			?.toUpperCase()
			.includes(inputValue.toUpperCase())
		const isRemarks = BasicDataModule.friendsRemarksMap
			.get(String((item as HistorySession).historicalUserSessionsId))
			?.toUpperCase()
			.includes(inputValue.toUpperCase())
		return isFriends || isGroupChat || isRemarks
	})
}
export interface FilterOption {
	children: string
	key: string
	value: string | number
	title?: string
	label?: string
}
/**
 * 不区分大小写
 * @param inputValue 搜索数据
 * @param option 展示数据
 * @returns
 */
export function filterOptionCaseInsensitive(inputValue: string, option: FilterOption) {
	const label = option.title ?? option.label ?? option.children
	return label.toUpperCase().includes(inputValue.toUpperCase())
}
import { isTrue } from '@/utils/tools'
/**
 * 判断表格数据是否为空
 * @param {Array} data
 * @param {String} key
 * @returns {string[]} 返回为空的数据
 */
export function isTableEmpty<T>(data: Array<T>, key: any[]): string[] {
	const empty: string[] = []
	data.forEach((item: any) => {
		key.find((res) => {
			if (!isTrue(item[res.value])) {
				empty.push(res.label)
			}
		})
		return
	})
	return empty
}
